<template>
  <div class="nutrition-analysis">
    <!-- 日期选择器 -->
    <el-card class="filter-section">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :shortcuts="shortcuts"
        @change="handleDateChange"
      />
    </el-card>

    <!-- 营养分析报告 -->
    <div class="analysis-content" v-loading="loading">
      <el-row :gutter="20" v-if="analysisData">
        <!-- 平均营养摄入 -->
        <el-col :span="12">
          <el-card class="analysis-card">
            <template #header>
              <div class="card-header">
                <span>平均每日营养摄入</span>
              </div>
            </template>
            <div class="nutrition-stats">
              <div class="stat-item">
                <span class="label">热量：</span>
                <span class="value">{{ analysisData.averageNutrition.avgCalories.toFixed(1) }} 千卡</span>
              </div>
              <div class="stat-item">
                <span class="label">蛋白质：</span>
                <span class="value">{{ analysisData.averageNutrition.avgProtein.toFixed(1) }} g</span>
              </div>
              <div class="stat-item">
                <span class="label">碳水化合物：</span>
                <span class="value">{{ analysisData.averageNutrition.avgCarbs.toFixed(1) }} g</span>
              </div>
              <div class="stat-item">
                <span class="label">脂肪：</span>
                <span class="value">{{ analysisData.averageNutrition.avgFat.toFixed(1) }} g</span>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 营养达标情况 -->
        <el-col :span="12">
          <el-card class="analysis-card">
            <template #header>
              <div class="card-header">
                <span>营养达标情况</span>
                <el-tag :type="getComplianceType(analysisData.compliance.overallStatus)">
                  {{ analysisData.compliance.overallStatus }}
                </el-tag>
              </div>
            </template>
            <div class="compliance-stats">
              <el-progress
                :percentage="analysisData.compliance.caloriesCompliance"
                :status="getProgressStatus(analysisData.compliance.caloriesCompliance)"
              >
                热量达标率
              </el-progress>
              <el-progress
                :percentage="analysisData.compliance.proteinCompliance"
                :status="getProgressStatus(analysisData.compliance.proteinCompliance)"
              >
                蛋白质达标率
              </el-progress>
              <el-progress
                :percentage="analysisData.compliance.carbsCompliance"
                :status="getProgressStatus(analysisData.compliance.carbsCompliance)"
              >
                碳水达标率
              </el-progress>
              <el-progress
                :percentage="analysisData.compliance.fatCompliance"
                :status="getProgressStatus(analysisData.compliance.fatCompliance)"
              >
                脂肪达标率
              </el-progress>
            </div>
          </el-card>
        </el-col>

        <!-- 建议改进 -->
        <el-col :span="24" v-if="analysisData.compliance.suggestions.length">
          <el-card class="analysis-card">
            <template #header>
              <div class="card-header">
                <span>营养建议</span>
              </div>
            </template>
            <div class="suggestions">
              <ul>
                <li v-for="(suggestion, index) in analysisData.compliance.suggestions" :key="index">
                  {{ suggestion }}
                </li>
              </ul>
            </div>
          </el-card>
        </el-col>

        <!-- 每日营养趋势图 -->
        <el-col :span="24">
          <el-card class="analysis-card">
            <template #header>
              <div class="card-header">
                <span>营养摄入趋势</span>
              </div>
            </template>
            <div class="trend-chart" ref="chartRef"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-empty v-else description="暂无分析数据" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import { getNutritionAnalysis } from '@/api/nutrition'
import * as echarts from 'echarts'

const store = useStore()
const loading = ref(false)
const dateRange = ref([])
const analysisData = ref(null)
const chartRef = ref(null)
let chart = null

// 获取登录用户ID
const userId = computed(() => store.state.user.userId || localStorage.getItem('userId'))

// 日期快捷选项
const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  }
]

// 获取分析数据
const fetchAnalysisData = async () => {
  if (!dateRange.value?.[0] || !dateRange.value?.[1]) {
    return
  }

  if (!userId.value) {
    ElMessage.warning('请先登录')
    return
  }

  loading.value = true
  try {
    const params = {
      startDate: new Date(dateRange.value[0].setHours(0, 0, 0, 0)).toISOString().split('T')[0],
      endDate: new Date(dateRange.value[1].setHours(23, 59, 59, 999)).toISOString().split('T')[0],
      userId: parseInt(userId.value)
    }

    const response = await getNutritionAnalysis(params)
    if (response) {
      // 设置默认值
      const defaultData = {
        averageNutrition: {
          avgCalories: 0,
          avgProtein: 0,
          avgCarbs: 0,
          avgFat: 0
        },
        compliance: {
          overallStatus: '一般',
          caloriesCompliance: 0,
          proteinCompliance: 0,
          carbsCompliance: 0,
          fatCompliance: 0,
          suggestions: []
        },
        dailyNutrition: []
      }

      // 合并响应数据和默认值
      analysisData.value = {
        ...defaultData,
        ...response.data,
        averageNutrition: {
          ...defaultData.averageNutrition,
          ...(response.data?.averageNutrition || {}),
          recommended: response.data?.averageNutrition?.recommended || 0
        },
        compliance: {
          ...defaultData.compliance,
          ...(response.data?.compliance || {}),
          recommended: response.data?.compliance?.recommended || 0
        },
        dailyNutrition: response.data?.dailyNutrition?.map(item => ({
          recommended: 0,
          ...item,
          calories: item.calories || 0,
          protein: item.protein || 0,
          carbs: item.carbs || 0,
          fat: item.fat || 0
        })) || []
      }

      setTimeout(() => {
        initChart()
      }, 0)
    }
  } catch (error) {
    ElMessage.info('您当前无营养摄入')
  } finally {
    loading.value = false
  }
}

// 处理日期变化
const handleDateChange = () => {
  fetchAnalysisData()
}

// 获取达标状态对应的类型
const getComplianceType = (status) => {
  const types = {
    '优秀': 'success',
    '良好': '',
    '一般': 'warning',
    '不佳': 'danger'
  }
  return types[status] || 'info'
}

// 获取进度条状态
const getProgressStatus = (percentage) => {
  if (percentage >= 90) return 'success'
  if (percentage >= 70) return ''
  if (percentage >= 50) return 'warning'
  return 'exception'
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value || !analysisData.value?.dailyNutrition) return

  if (chart) {
    chart.dispose()
  }
  chart = echarts.init(chartRef.value)

  const dates = analysisData.value.dailyNutrition.map(item => item.date)
  const series = [
    {
      name: '热量',
      type: 'line',
      data: analysisData.value.dailyNutrition.map(item => item.calories || 0)
    },
    {
      name: '蛋白质',
      type: 'line',
      data: analysisData.value.dailyNutrition.map(item => item.protein || 0)
    },
    {
      name: '碳水',
      type: 'line',
      data: analysisData.value.dailyNutrition.map(item => item.carbs || 0)
    },
    {
      name: '脂肪',
      type: 'line',
      data: analysisData.value.dailyNutrition.map(item => item.fat || 0)
    }
  ]

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['热量', '蛋白质', '碳水', '脂肪']
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        formatter: (value) => {
          return value?.split('T')[0] || ''
        }
      }
    },
    yAxis: {
      type: 'value'
    },
    series
  }

  chart.setOption(option)
}

// 监听窗口大小变化
window.addEventListener('resize', () => {
  chart?.resize()
})

onMounted(() => {
  dateRange.value = shortcuts[0].value()
  setTimeout(() => {
    fetchAnalysisData()
  }, 0)
})

onUnmounted(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
})
</script>

<style lang="scss" scoped>
.nutrition-analysis {
  padding: 20px;

  .filter-section {
    margin-bottom: 20px;
  }

  .analysis-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .nutrition-stats,
    .compliance-stats {
      .stat-item {
        margin-bottom: 12px;

        .label {
          color: var(--el-text-color-secondary);
        }

        .value {
          margin-left: 8px;
          font-weight: 500;
        }
      }
    }

    .compliance-stats {
      :deep(.el-progress) {
        margin-bottom: 16px;
      }
    }

    .suggestions {
      ul {
        margin: 0;
        padding-left: 20px;

        li {
          margin-bottom: 8px;
          color: var(--el-text-color-regular);
        }
      }
    }

    .trend-chart {
      height: 400px;
    }
  }
}

@media (max-width: 768px) {
  .nutrition-analysis {
    padding: 10px;
  }
}
</style> 